//
//  ShopViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/16.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "ShopViewController.h"
#import "ShopCell.h"
#import "ShopCellHeadVeiw.h"
#import "ShopCellFootView.h"
#import "LookAllViewController.h"
#import "MBProgressHUD+LJ.h"

#import <AMapLocationKit/AMapLocationKit.h>


@interface ShopViewController ()<UITableViewDelegate,UITableViewDataSource,AMapLocationManagerDelegate>
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property(nonatomic,assign)int isRejectAndBackLoaction;
@end

@implementation ShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isRejectAndBackLoaction = 0;//初始值；
    //数据源
    self.dataSource = [NSMutableArray array];
    [self tableViewAndHeaderView];
    NSString *status = [[NSUserDefaults standardUserDefaults]objectForKey:@"CLAuthorizationStatus"];
    if(status.length){
        [AppDelegate appDealegate].latitude = @"";
        [AppDelegate appDealegate].longitude = @"";
        [AppDelegate appDealegate].cityId = @"";
        [AppDelegate appDealegate].cityName = @"";
        [self loadData];
    }
    //先从本地取位置信息 如果本地没有 就去定位
    NSString *cityName = [[NSUserDefaults standardUserDefaults]objectForKey:@"cityName"];
    NSString *cityId = [[NSUserDefaults standardUserDefaults]objectForKey:@"cityCode"];
    NSString *lat = [[NSUserDefaults standardUserDefaults]objectForKey:@"lat"];
    NSString *lon = [[NSUserDefaults standardUserDefaults]objectForKey:@"lon"];
    if(cityName.length){
        //保存到应用级别
        [AppDelegate appDealegate].cityId = cityId;
        [AppDelegate appDealegate].cityName = cityName;
        [AppDelegate appDealegate].latitude = lat;
        [AppDelegate appDealegate].longitude = lon;
        [self loadData];
        [self sendCityInfo];
    }else{
        //定位
        [self getUserLoaction];
    }
}
-(void)getUserLoaction{
      self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer];
    //设置不允许系统暂停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    //设置允许在后台定位
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    //设置定位超时时间
    [self.locationManager setLocationTimeout:5];
    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:3];

}
-(void)locationing{
       [MBProgressHUD showActivityMessageInWindow:@"正在获取位置..."];
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
    __weak typeof(self)  weakSelf  = self;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if(location){
            CLLocationCoordinate2D coordinate = location.coordinate;
            NSString  *lat = [NSString stringWithFormat:@"%f",coordinate.latitude];
            NSString  *lon = [NSString stringWithFormat:@"%f",coordinate.longitude];
            DLog(@"当前维度---%@",lat);
            DLog(@"当前精度---%@",lon);
            [AppDelegate appDealegate].latitude = lat;
            [AppDelegate appDealegate].longitude = lon;
            //将位置保存本地
            [[NSUserDefaults standardUserDefaults]setObject:lat forKey:@"lat"];
            [[NSUserDefaults standardUserDefaults]setObject:lon  forKey:@"lon"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
        }
        if (regeocode){
            DLog(@"city--%@",regeocode.city);
            DLog(@"cityCode--%@",regeocode.citycode);
            //保存到应用级别
            [AppDelegate appDealegate].cityId = regeocode.citycode;
            [AppDelegate appDealegate].cityName = regeocode.city;
            //将位置保存本地
            [[NSUserDefaults standardUserDefaults]setObject:regeocode.city forKey:@"cityName"];
            [[NSUserDefaults standardUserDefaults]setObject:regeocode.citycode forKey:@"cityCode"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            //加载数据
            [MBProgressHUD dismiss];
            [weakSelf sendCityInfo];
            if(self.isRejectAndBackLoaction!=1){
                [weakSelf loadData];
            }
        }
    }];
}
//发送位置通知
-(void)sendCityInfo{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"cityInfo" object:nil];
       if(self.isRejectAndBackLoaction){
         [[NSNotificationCenter defaultCenter]postNotificationName:@"reLoadDataWhenLocationChanged" object:nil];
    }
}

//定位失败的代理方法
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error{
    if (error){
        DLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
        if (error.code == AMapLocationErrorLocateFailed)
        {
            return;
        }
    }
}
//定位权限状态改变时回调函数
- (void)amapLocationManager:(AMapLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    DLog(@"定位权限状态改变时回调函数---%ld",status);
    if(status==4){
        if(self.isRejectAndBackLoaction==1){
            self.isRejectAndBackLoaction =2;
        }
         [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"CLAuthorizationStatus"];
         [[NSUserDefaults standardUserDefaults]synchronize];
        [self locationing];
    }
    if(status ==2){//点击了不允许定位
        self.isRejectAndBackLoaction = 1;//被拒
         [MBProgressHUD dismiss];
        [AppDelegate appDealegate].latitude = @"";
        [AppDelegate appDealegate].longitude = @"";
        [AppDelegate appDealegate].cityId = @"";
        [AppDelegate appDealegate].cityName = @"";
        [self sendCityInfo];
        [self loadData];
        [[NSUserDefaults standardUserDefaults]setObject:@"2"  forKey:@"CLAuthorizationStatus"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
}

-(void)loadData{
    //2.6获取主页面商场列表
     [MBProgressHUD showLoadingGif];
     NSString *cityId =  [AppDelegate appDealegate].cityId;
      NSDictionary *paraDic = @{
                              @"marketSize":@"20",            //各类型商场展示个数
                              @"cityId":cityId,                        //行政区划标识（默认石家庄）
                              };
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:HOMEPAGEBYMARKET paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"获取主页面商场列表--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *listArr = resultDic[@"data"];
            if([listArr isKindOfClass:[NSNull class]]){
                [MBProgressHUD dismissHUD];
                return ;
            }
            for(NSDictionary *dic in listArr){
                 NSArray *contentArr = dic[@"content"];
                if(contentArr.count){
                ShopCellGroup *group = [[ShopCellGroup alloc]init];
                group.markettype = dic[@"markettype"];
                group.markettypeid = dic[@"markettypeid"];
//                group.iconName = iamgeArr[i];
                NSMutableArray *arr = [NSMutableArray array];
                for(NSDictionary *dic in contentArr){
                    ShopCellModel *model = [ShopCellModel modelWithDic:dic];
                    [arr addObject:model];
                    group.collectionArray = arr.copy;
                }
                 [weakSelf.dataSource addObject:group];
                }
            }
            [weakSelf.tableV reloadData];
            weakSelf.tableV.hidden = NO;
            [MBProgressHUD dismissHUD];
            [weakSelf checkUpNewVersion];
        }else{
              [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

- (void)tableViewAndHeaderView{
    //表视图
    self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 1, Main_Screen_Width, Main_Screen_Height-49-56-44+2) style:UITableViewStyleGrouped];
    self.tableV.showsVerticalScrollIndicator = NO;
    self.tableV.backgroundColor = [UIColor colorWithRed:242./255 green:242./255 blue:242./255 alpha:1.];
    self.tableV.delegate = self;
    self.tableV.dataSource =self;
    [self.view addSubview:self.tableV];
    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableV.hidden = YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;    {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        NSString *ident=@"actell";
        ShopCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
        if(cell==nil){
            cell=[[[NSBundle mainBundle]loadNibNamed:@"ShopCell" owner:self options:nil]lastObject];
        }
    ShopCellGroup *group = self.dataSource[indexPath.section];
    cell.dataSource = group.collectionArray;
    return cell;
 }

//自定义头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *headID = @"head";
    ShopCellHeadVeiw *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
    if(headView==nil){
        headView = [[[NSBundle mainBundle]loadNibNamed:@"ShopCellHeadVeiw" owner:self options:nil]lastObject];
    }
    ShopCellGroup *model = self.dataSource[section];
    headView.model = model;
    return headView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NSString *headID = @"footer";
    ShopCellFootView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
    if(footerView==nil){
        footerView = [[[NSBundle mainBundle]loadNibNamed:@"ShopCellFootView" owner:self options:nil]lastObject];
    }
    ShopCellGroup *model = self.dataSource[section];
    footerView.model = model;
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 187;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;{
    return 37;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;{
    return 57;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if(scrollView.contentOffset.y+self.tableV.height>=self.tableV.contentSize.height){
         [[NSNotificationCenter defaultCenter]postNotificationName:@"scrollToBottom" object:nil];
    }
    if(scrollView.contentOffset.y<0){
         [[NSNotificationCenter defaultCenter]postNotificationName:@"scrollToTop" object:nil];
    }
}

-(void)checkUpNewVersion{
//    NSString *versionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *build = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSDictionary *prama = @{@"clientType":@"0",
                            @"versionCode":build,
                            @"phoneType":@"1"
                            };
    [Tools AFNetworkingRequestTypePostWithUrl:VERSION paramters:prama afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"版本检查更新----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) return ;
            if([dataDic[@"status"] isEqualToString:@"true"]){//需要更新
                if([dataDic[@"url"] isKindOfClass:[NSNull class]]) return;
                [AppDelegate appDealegate].updateUrl = dataDic[@"url"];
                NSString *version = dataDic[@"versionCode"];
                if([version isKindOfClass:[NSNull class]]) return;
                BOOL isEmergency = [dataDic[@"ifMust"] boolValue];
                NSString *updateInfo = dataDic[@"content"];
                if([updateInfo isKindOfClass:[NSNull class]]) return;
                 NSString *v = [[NSUserDefaults standardUserDefaults]objectForKey:@"version"];
                if(v.length&&[version isEqualToString:v]) return;
                if(isEmergency) {//强制更新
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"%@%@", @"发现新版本", version] message:updateInfo preferredStyle:UIAlertControllerStyleAlert];
                    UIView *subView1 = alertController.view.subviews[0];
                    UIView *subView2 = subView1.subviews[0];
                    UIView *subView3 = subView2.subviews[0];
                    UIView *subView4 = subView3.subviews[0];
                    UIView *subView5 = subView4.subviews[0];
                    UILabel *message = subView5.subviews[1];
                    message.textAlignment = NSTextAlignmentLeft;
                    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"立即去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSString *updateUrl = [AppDelegate appDealegate].updateUrl;
                        if (updateUrl.length) {
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updateUrl]];
                        }
                    }];
                    [alertController addAction:okAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                }else{
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"%@%@", @"发现新版本", version] message:updateInfo preferredStyle:UIAlertControllerStyleAlert];
                    UIView *subView1 = alertController.view.subviews[0];
                    UIView *subView2 = subView1.subviews[0];
                    UIView *subView3 = subView2.subviews[0];
                    UIView *subView4 = subView3.subviews[0];
                    UIView *subView5 = subView4.subviews[0];
                    UILabel *message = subView5.subviews[1];
                    message.textAlignment = NSTextAlignmentLeft;
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"忽略此版本" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        [[NSUserDefaults standardUserDefaults] setObject:version forKey:@"version"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }];
                    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"立即去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSString *updateUrl = [AppDelegate appDealegate].updateUrl;
                        if (updateUrl.length) {
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updateUrl]];
                        }
                    }];
                    [alertController addAction:cancelAction];
                    [alertController addAction:okAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                }
            }
        }
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
